package com.kuang.demo.controller.wx;

import com.kuang.demo.bean.BaseRespVo;
import com.kuang.demo.bean.WXLoginBean;
import com.kuang.demo.bo.zzywx.auth.InfoExpireToken;
import com.kuang.demo.bo.zzywx.auth.UserInfo;
import com.kuang.demo.bo.zzywx.auth.UsernamePwd;
import com.kuang.demo.config.wx.MyToken;
import com.kuang.demo.mapper.wx.WXAuthMapper;
import com.kuang.demo.service.wx.WXAuthService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;

@RestController
@RequestMapping("/wx/auth")
public class WXAuthController {

    @Autowired
    WXAuthService wxAuthService;

    //登录接口
    @RequestMapping("/login")
    public BaseRespVo LoginControl(@RequestBody UsernamePwd usernamePwd){

        //TODO:捕获异常可以优化
        Subject subject = SecurityUtils.getSubject();
        try{
            subject.login(new MyToken(usernamePwd.getUsername(),usernamePwd.getPassword(),"wx"));
            String principal = (String) subject.getPrincipal();
            String id = (String) subject.getSession().getId();

            UserInfo userInfo = wxAuthService.selectByUsername(usernamePwd.getUsername());
            InfoExpireToken infoExpireToken = new InfoExpireToken();
            infoExpireToken.setUserInfo(userInfo);
            infoExpireToken.setToken(id);
            infoExpireToken.setTokenExpire("2020-11-05T19:57:17.208");


            return BaseRespVo.ok(infoExpireToken);
        }catch (Exception e){
            System.out.println("权限或者密码不对");
        }
        BaseRespVo baseRespVo = new BaseRespVo();
        baseRespVo.setErrno(605);
        baseRespVo.setErrmsg("用户密码不对或没有权限");

        return baseRespVo;
    }

    //登出接口
    @RequestMapping("logout")
    public BaseRespVo LoginOut(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();

        return BaseRespVo.ok();
    }
}
